package main

import (
	"os"

	"github.com/sirupsen/logrus"
	log "github.com/sirupsen/logrus"
)

type myHook struct {
}

// Levels 只定义error和panic等级的日志，其他日志等级不会触发hook
func (h *myHook) Levels() []log.Level {
	return []log.Level{
		log.ErrorLevel,
		log.PanicLevel,
	}
}

// Fire 将异常日志写入到指定日志文件中
func (h *myHook) Fire(entry *log.Entry) error {
	file, err := os.OpenFile("data/error.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
	if err != nil {
		return err
	}

	if _, err := file.Write([]byte(entry.Message)); err != nil {
		return err
	}

	return nil
}

func logrusExample() {
	log.Info("Study logrus example")

	// a. logrus一般使用
	// 设置日志格式为json
	log.SetFormatter(&log.JSONFormatter{})

	// 设置日志级别为warn以上
	log.SetLevel(log.WarnLevel)

	log.WithFields(log.Fields{
		"animal": "walrus",
		"size":   10,
	}).Info("A group of walrus emerges from the ocean")
	log.WithFields(log.Fields{
		"omg":    true,
		"number": 122,
	}).Warn("The groups's number increased tremendously!")
	/*
		log.WithFields(log.Fields{
			"omg":    true,
			"number": 100,
		}).Fatal("The ice breaks")
	*/

	// b. 创建logger
	logger := logrus.New()
	// 设置日志的输出为logrus实例
	logger.Out = os.Stdout
	// 设置日志的输出格式
	logger.Formatter = &logrus.JSONFormatter{}

	logger.WithFields(logrus.Fields{
		"animal": "penguin",
		"size":   20,
	}).Info("A group of penguin emerges from the ocean")

	// c. Fields
	// 设定固定的Field，比如HTTP请求
	requestLogger := logger.WithFields(logrus.Fields{"request_id": 45135825544, "user_ip": "147.52.32.8"})
	requestLogger.Info("something happened on that request")
	requestLogger.Warn("something not great happened")

	// d. Hook，示例将错误和异常日志写入到文件中
	log.AddHook(&myHook{})
	log.Error("some errors\n")
	// log.Panic("some panic\n")
	log.Println("hello world")
}
